package com.icode.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icode.common.utils.HttpUtils;
import com.icode.gulimall.member.excption.PhoneExistException;
import com.icode.gulimall.member.excption.UserNameExistException;
import com.icode.gulimall.member.vo.MemberLoginVo;
import com.icode.gulimall.member.vo.MemberRegistVo;
import com.icode.gulimall.member.dao.MemberLevelDao;
import com.icode.gulimall.member.entity.MemberLevelEntity;
import com.icode.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icode.common.utils.PageUtils;
import com.icode.common.utils.Query;

import com.icode.gulimall.member.dao.MemberDao;
import com.icode.gulimall.member.entity.MemberEntity;
import com.icode.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;
    @Autowired
    MemberDao memberDao;

    @Override
    public MemberEntity acctLogin(MemberLoginVo loginVo) {
        String loginAcct = loginVo.getLoginAcct();
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<MemberEntity>().eq("username", loginAcct).or().eq("mobile", loginAcct).or().eq("email", loginAcct);
        MemberEntity memberEntity = this.baseMapper.selectOne(queryWrapper);
        if (memberEntity != null) {
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            return passwordEncoder.matches(loginVo.getPassword(), passwordDb) ? memberEntity : null;
        } else {
            return null;
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void memberRegist(MemberRegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity defaultLevel = memberLevelDao.getDefaultLevel();
        if (defaultLevel != null) {
            memberEntity.setLevelId(defaultLevel.getId());
        }
        //检查用户名和手机号是否唯一，为了让Controller感知异常，异常处理机制
        checkPhoneUnique(registVo.getPhone());
        checkUsernameUnique(registVo.getUserName());

        memberEntity.setMobile(registVo.getPhone());
        memberEntity.setUsername(registVo.getUserName());
        //密码加密 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(registVo.getPassword());
        memberEntity.setPassword(encode);

        this.save(memberEntity);
    }

    public void checkUsernameUnique(String userName) throws UserNameExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer username = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0)
            throw new UserNameExistException();
    }

    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) throws Exception {
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));
        //没有此用户就创建
        if (memberEntity == null) {
            memberEntity = new MemberEntity();
            memberEntity.setSocialUid(socialUser.getUid());
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            memberEntity.setCreateTime(new Date());
            MemberLevelEntity defaultLevel = memberLevelDao.getDefaultLevel();
            if (defaultLevel != null) {
                memberEntity.setLevelId(defaultLevel.getId());
            }
            //抓取微博公开api中的用户信息
            Map<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");

                memberEntity.setNickname(name);
                memberEntity.setGender("m".equals(gender) ? 1 : 0);
                memberEntity.setHeader(profileImageUrl);
            }
            memberDao.insert(memberEntity);
        }
        return memberEntity;
    }

    public void checkPhoneUnique(String phone) throws PhoneExistException {
        MemberDao baseMapper = this.baseMapper;
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0)
            throw new PhoneExistException();
    }

}